package org.alanlau.hystrix.simple;

import com.netflix.hystrix.*;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.netflix.hystrix.strategy.concurrency.HystrixRequestContext;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 线程隔离策略配置
 *
 * @author liukun
 * @version 1.0
 * @date 2020/9/14 20:19
 */
public class MyHystrixCommand5 extends HystrixCommand<String> {
    private final String name;
    private static final HystrixCommandKey GETTER_KEY = HystrixCommandKey.Factory.asKey("MyGroup");

    public MyHystrixCommand5(String name) {
        super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey
                .Factory.asKey("MyGroup")).andCommandKey(GETTER_KEY));
        this.name = name;
    }

    @Override
    protected String run() throws Exception {
        System.err.println("get data");
        return this.name + ":" + Thread.currentThread().getName();
    }

    @Override
    protected String getCacheKey() {
        return String.valueOf(this.name);
    }

    public static void flushCache(String name) {
        HystrixRequestCache.getInstance(GETTER_KEY, HystrixConcurrencyStrategyDefault.getInstance()).clear(name);
    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        HystrixRequestContext context = HystrixRequestContext.initializeContext();

        String result = new MyHystrixCommand5("alan").execute();
        System.out.println(result);

        // 清除缓存
        flushCache("alan");

        Future<String> future = new MyHystrixCommand5("alan").queue();
        System.out.println(future.get());
        context.shutdown();
    }
}
